﻿using ControlHelper.Attributes;
using Creator.Access.Core;
using Creator.Core.Base;
using System;
using System.Collections;
using System.Data;

namespace Creator.Core.Component
{
    [ComponentMenu("基础/数据读取")]

    public class ReadDataComponent : LogicComponet
    {
        public ReadDataComponent(BaseObject baseObject) : base(baseObject)
        {
        } 
        /// <summary>
        /// 允许在编辑窗口绘制数据
        /// </summary>
        public override bool StartOnEditor => true;
        [NickName("读取间隔(秒)")]
        public float Intervarl { get; set; } = 3;
        [NickName("连接方式")]
        public OperationComponent Operation { get; set; }

        [NickName("数据结果载体")]
        public DataListComponent DataList { get; set; }
 
        public override string Name => "读取数据";

        private double currentTime = 0;

        public override event Action<object, object> OnInit;

        public override event Action<object, object> OnEditorEvent;
        public override void Init()
        {
            base.Init();
            SetDataList(GetResults()); 
        }

        public override void Run(double deltaTime)
        {
            base.Run(deltaTime);
            if (Entrey.realTime > currentTime  + Intervarl)
            { 
                SetDataList(GetResults());
                currentTime = Entrey.realTime;
            } 
        } 

        public override void OnEditor()
        {
            base.OnEditor();
            var reuslt = GetResults();
            OnEditorEvent?.Invoke(this, reuslt); 
            SetDataList(reuslt); 
        }
        //--------------------- 私有方法 ---------------
        private void SetDataList(IList data)
        {
            if (DataList == null)
            {
                //todo:记录错误
                return;
            }
            DataList.Data = data;
        }
        /// <summary> 从操作对象中尝试获取数据 </summary> 
        private IList GetResults()
        { 
            var oc = Operation.Operation;
            if (Operation == null || oc == null) return null;

            if (!oc.Connect())
            {
                return null;
            }

            var results = oc.GetResults();
            IList data = null;
            foreach (var result in results)
            {
                if (result is SQLResult sqlRes && sqlRes.Data is DataTable dt)
                { 
                    data = dt.ToEntityList(sqlRes.TargetType);
                }
            }

            return data;
        }
    }
}
